package com.lanou3g.ptp.student.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.organize.service.ClazzService;
import com.lanou3g.ptp.organize.service.CollegeService;
import com.lanou3g.ptp.organize.service.MajorService;
import com.lanou3g.ptp.organize.service.SchoolService;
import com.lanou3g.ptp.student.mapper.StudentMapper;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.student.utils.ExcelUtil;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.ptp.utils.ExcelUtils;
import com.lanou3g.ptp.vo.TreeNode;
import com.lanou3g.ptp.wx.service.WxService;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service(timeout = 5000)
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Reference(lazy = true)
    private UserService userService;

    @Reference(lazy = true)
    private SchoolService schoolService;

    @Reference(lazy = true)
    private ClazzService clazzService;

    @Reference(lazy = true)
    private CollegeService collegeService;

    @Reference(lazy = true)
    private MajorService majorService;

    @Reference(lazy = true)
    private WxService wxService;



//    row1.createCell(0).setCellValue("学号");
//        row1.createCell(1).setCellValue("名字");
//        row1.createCell(2).setCellValue("电话");
//        row1.createCell(3).setCellValue("学校");
//        row1.createCell(4).setCellValue("学院");
//        row1.createCell(5).setCellValue("专业");
//        row1.createCell(6).setCellValue("班级");

    private String no = "学号";
    private String name = "名字";
    private String tel = "电话";
    private String school = "学校";
    private String college = "学院";
    private String major = "专业";
    private String clazz = "班级";
    private List<String> columns = Arrays.asList(no, name, tel, school, college, major, clazz);
    private int noIndex = columns.indexOf(no);
    private int nameIndex = columns.indexOf(name);
    private int telIndex = columns.indexOf(tel);
    private int schoolIndex = columns.indexOf(school);
    private int majorIndex = columns.indexOf(major);
    private int collegeIndex = columns.indexOf(college);
    private int clazzIndex = columns.indexOf(clazz);
    private int cols = columns.size();
    private int max = 300;


    //查询所有学生
    @Override
    public PageInfo<Student> findAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Student> students = studentMapper.studentAll();
        studentMapper.studentAll();
        for (Student student : students) {
            //取出user  无密码
            User user = userService.userById(student.getId());
            student.setUser(user);
        }
        return new PageInfo<>(students);
    }


    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.studentAll();
        studentMapper.studentAll();
        for (Student student : students) {
            //取出user  无密码
            User user = userService.userById(student.getId());
            student.setUser(user);
        }
        return students;
    }


    //通过id查询
    @Override
    public Student studentById(Long id) {
        return studentMapper.studentById(id);
    }

    //根据名字模糊查询
    @Override
    public PageInfo<Student> ByName(Integer page, Integer size, String name) {
        PageHelper.startPage(page, size);
        List<Student> students = new ArrayList<>();
        List<User> user = userService.userByName(name);
        for (User user1 : user) {
            Student student = studentMapper.studentById(user1.getId());
            student.setUser(user1);
            students.add(student);
        }
        return new PageInfo<>(students);
    }


    //根据id 删除
    @Override
    public int deleteById(Long id) {
//        int il = 0;
        int i = userService.deleteById(id);
//        if (i > 0) {
//            il = studentMapper.deleteById(id);
//        }
        return i;
    }

    //根据id 删除多个
    @Override
    public int deleteByIds(List<Long> id) {
        int il = 0;
        for (Long aLong : id) {
            il += userService.deleteById(aLong);
//            if (i > 0) {
//                il += studentMapper.deleteById(aLong);
//            }T
        }
        return il;
    }

    //修改数据
    @Override
    public int upStuById(Student student) {
        int l = 0;
        Date date = new Date();
        student.setUpdateTime(date);//更新修改时间
        int i = studentMapper.upStudent(student);
        if (i > 0) {
            try {
                User user = student.getUser();
                user.setUpdateTime(date);//更新时间 赋值给用户属性
//                user.setStatus(student.getStatus());//更新时间 赋值给用户属性
                l = userService.upUser(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //添加学生
    @Override
    public int insetStudent(Student student) {
        Date date = new Date();
        User user = student.getUser();
        user.setStatus(0);
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //更新用户
        Long id = null;
        try {
            id = userService.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //更新学生类
        int l = 0;
        if (id != null) {
            student.setId(id);
            if (student.getCollegeId() != null) {
                College college = collegeService.findById(student.getCollegeId());
                student.setSchoolId(college.getSchoolId());
            }
            student.setStatus(0);
            student.setCreateTime(date);
            student.setUpdateTime(date);
            l = studentMapper.addStudent(student);
        }
        return l;
    }

    //导入学生excel
    @Override
    public int excelToStudentInfo(byte[] bytes) {
        int count = 0;
        //把字节数组转回流
        InputStream studentUploadFile = new ByteArrayInputStream(bytes);
//        ArrayList<Student> students = new ArrayList<>();
        try {
            XSSFWorkbook wb = new XSSFWorkbook(studentUploadFile);
            //获取第0页信息
            XSSFSheet sheet = wb.getSheetAt(0);
            if (sheet != null) {

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {

                    Row row = sheet.getRow(i);

                    Student student = new Student();
                    User user = new User();
                    student.setUser(user);

                    String collegeExcel = ExcelUtil.getCellValue(row.getCell(collegeIndex));
                    College college = collegeService.findByName(collegeExcel);
                    student.setCollegeId(college.getId());

                    String schoolExcel = ExcelUtil.getCellValue(row.getCell(schoolIndex));
                    School school = schoolService.findByName(schoolExcel);
                    student.setSchoolId(school.getId());

                    String noExcel = ExcelUtils.getCellValue(row.getCell(noIndex));
                    user.setNo(noExcel);
                    String nameExcel = ExcelUtils.getCellValue(row.getCell(nameIndex));
                    user.setName(nameExcel);
                    String telExcel = ExcelUtil.getCellValue(row.getCell(telIndex));
                    user.setTel(telExcel);


                    String major = ExcelUtil.getCellValue(row.getCell(majorIndex));
                    if (major != null) {
                        Long majorId = majorService.findByName(major).getId();
                        student.setMajorId(majorId);
                    }

                    String clazzExcel = ExcelUtil.getCellValue(row.getCell(clazzIndex));
                    if (clazz != null) {
                        Clazz clazz = clazzService.findByName(clazzExcel);
                        student.setClazzId(clazz.getId());
                    }
                    count += insetStudent(student);
                }
                return count;
            }
            return count;
        } catch (IOException e) {
            e.printStackTrace();
            return count;
        }
    }


    //表格数据 加入数据库
    @Override
    public boolean studentExcel(List<Student> students) {
        //记录 加入条数总数
        int sum = 0;
        boolean b = false;
        //加入数据
        for (Student student : students) {
            int i = insetStudent(student);
            sum += i;
        }
        //判定是否加入条数和信息总数一直  返回结果
        if (sum == students.size()) {
            b = true;
        }
        return b;
    }

    //导出模板
    @Override
    public byte[] excelStudentModel() {

        XSSFWorkbook sheets = new XSSFWorkbook();
        Sheet sheet = sheets.createSheet("码页");

        //负责表格对齐方式
        CellStyle cellStyle1 = sheets.createCellStyle();
        cellStyle1.setAlignment(HorizontalAlignment.LEFT);//设置单元格水平方向对齐方式  居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格垂直方向对齐方式  居中

        //设置表头字体样式
        XSSFCellStyle cellStyle4 = sheets.createCellStyle();
        XSSFFont font1 = sheets.createFont();  //设置字体样式
        font1.setFontName("微软雅黑");
        font1.setFontHeightInPoints((short) 12);//设置字号
        font1.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());//设置字体颜色
        cellStyle4.setFont(font1);  //字体风格放入  风格

        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 15 * 256);
        row1.setHeightInPoints(30);//设置行的高度是50
        row1.createCell(0).setCellValue("学号");
        row1.createCell(1).setCellValue("名字");
        row1.createCell(2).setCellValue("电话");
        row1.createCell(3).setCellValue("学校");
        row1.createCell(4).setCellValue("学院");
        row1.createCell(5).setCellValue("专业");
        row1.createCell(6).setCellValue("班级");
        row1.setRowStyle(cellStyle1);
        row1.setRowStyle(cellStyle4);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            sheets.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os.toByteArray();
    }

    //查询当前班级有多少人
    @Override
    public Long findClazzId(long clazzId) {
        Long clazzId1 = studentMapper.findClazzId(clazzId);
        System.out.println(clazzId1);
        return clazzId1;
    }

    @Override
    public Student findById(Long studentId) {
        return studentMapper.findById(studentId);
    }

    @Override
    public PageInfo<Student> findBySchoolId(Long schoolId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Student> studentList = studentMapper.findBySchoolId(schoolId);
//        completeStudentList(studentList);
        return new PageInfo<>(studentList);
    }

    @Override
    public List<TreeNode> treeByMajorId(Long majorId) {

        return this.studentMapper.treeByMajorId(majorId);
    }

    @Override
    public boolean completeStudent(Student student, String code) {
        if (code != null) {
            String openId = wxService.getOpenId(code);
            student.setOpenId(openId);
        }
        student.setUpdateTime(new Date());
        int i = studentMapper.upStudent(student);
        return i > 0;
    }

    private void completeStudentList(List<Student> studentList) {
        for (Student student : studentList) {
            User user = userService.userById(student.getId());
            user.setPassword(null);
            student.setUser(user);
            Long collegeId = student.getCollegeId();
            Long majorId = student.getMajorId();
            Long clazzId = student.getClazzId();
            College college = collegeService.findById(collegeId);
            student.setCollegeName(college.getName());
            Major major = majorService.findById(majorId);
            student.setMajorName(major.getName());
            Clazz clazz = clazzService.findById(clazzId);
            student.setClazzName(clazz.getName());
        }
    }
}


